package net.chasing.androidbaseconfig.view;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProvider;

/**
 * 注意：使用自定义{@link net.chasing.androidbaseconfig.adapter.BaseFragmentPagerAdapter}
 * 切换的时候是不会销毁Fragment的，只会调用onDestroyView，没有调用到onDestroy，
 * 所以在onCreate等步骤进行初始化时，需要进行判断，避免重复初始化
 */
public abstract class BaseFragment<VM extends BaseViewModel, Binding extends ViewDataBinding>
        extends BaseMVCFragment<Binding> {

    protected VM mViewModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        if (needReset) {
            mViewModel = new ViewModelProvider(this).get(bindViewModel());
            getLifecycle().addObserver(mViewModel);
        }
        return view;
    }

    protected abstract Class<VM> bindViewModel();

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (needReset) {
            observeData();
            if (getArguments() == null)
                mViewModel.parseBundle(new Bundle());
            else
                mViewModel.parseBundle(getArguments());
            mViewModel.initResource();
        }
    }

    protected abstract void observeData();
}
